import {
  Button,
  Card,
  Table,
  Typography,
  Tag,
  Pagination,
  Space,
  Popconfirm,
} from 'antd';
import { useContext } from 'react';
import { context } from '../index';
import { formatTime } from '@/utils/index';

const Index = () => {
  const { dataSource, count, currentPage, onSizeChange, onRemove, modalOpen } =
    useContext(context);

  // 列信息
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render(text: string) {
        return <span>{text === '1' ? '男' : '女'}</span>;
      },
    },
    {
      title: '城市',
      dataIndex: 'city',
      // 通过width属性来空值每一列的宽度，默认由内容的长度来决定
      width: 300,
    },
    {
      title: '出生年月',
      dataIndex: 'birthday',
      render(text: number) {
        return formatTime(text, 'd');
      },
    },
    {
      title: '操作',
      render(text: string, record: any) {
        return (
          <Space>
            <Button onClick={() => modalOpen('edit', record)}>编辑</Button>
            <Popconfirm
              title="你确定要删除吗?"
              onConfirm={() => confirm(record._id)}
              onCancel={cancel}
              okText="Yes"
              cancelText="No"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const confirm = (id: string) => {
    // console.log('confirm', id);
    onRemove(id);
  };

  const cancel = () => {
    console.log('cancel');
  };

  // 页码或者条数改变的事件
  const handleChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    onSizeChange(page, pageSize);
  };

  return (
    <Card
      title="学员管理"
      extra={
        <Button type="primary" onClick={() => modalOpen('add')}>
          新增
        </Button>
      }
    >
      {/* 一般都会把默认的分页去掉，自己去重新添加分页 */}
      <Table dataSource={dataSource} columns={columns} pagination={false} />
      <Pagination
        defaultCurrent={currentPage}
        total={count}
        style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}
        onChange={handleChange}
      />
    </Card>
  );
};

export default Index;
